package com.anjubao.parking.municipal.roadside.utils;

import com.alibaba.fastjson.JSONObject;
import com.anjubao.parking.municipal.common.dto.ApiResult;
import com.anjubao.parking.municipal.common.global.BusinessCodeEnum;
import com.anjubao.parking.municipal.common.utils.MunicipalParkingUtils;
import com.anjubao.parking.municipal.common.utils.U;
import com.anjubao.parking.municipal.parkinglot.dto.EntryEnterDTO;
import com.anjubao.parking.municipal.parkinglot.dto.EntryLeaveDTO;
import com.anjubao.parking.municipal.parkinglot.dto.ParkingTotalFeeDto;
import com.anjubao.parking.municipal.parkinglot.feign.ParkingLotFeignService;
import com.anjubao.parking.municipal.roadside.common.Constants;
import com.anjubao.parking.municipal.roadside.dto.CarInMessageDto;
import com.anjubao.parking.municipal.roadside.dto.CarOutMessageDto;
import com.anjubao.parking.municipal.roadside.feign.ParkingLotFeignClient;
import com.anjubao.parking.municipal.roadside.form.InParkingRecordForm;
import com.anjubao.parking.municipal.roadside.model.ParkingRecord;
import com.anjubao.parking.municipal.roadside.model.PayRecord;
import jdk.nashorn.internal.runtime.regexp.JoniRegExp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class ParkingUtils {

    private static final Logger logger = LoggerFactory.getLogger(ParkingUtils.class);

    @Autowired
    private HttpUtils httpUtils;
    @Value("${imgPrefix}")
    private String imgPrefix;
    @Autowired
    private ParkingLotFeignClient parkingLotFeignClient;

    /**
     * 图片上传
     * @param base64Image
     * @return
     */
    public String uploadImage(String uploadImageUrl,String base64Image){
        Map<String, String> map = new HashMap<>();
        map.put("base64", base64Image);
        String res = httpUtils.postForm(uploadImageUrl,map);
        JSONObject resObject= JSONObject.parseObject(res);
        if ((Integer)resObject.get("code")!=2000){
            logger.info("图片上传失败！！！");
            return "";
        }
        return resObject.getJSONObject("result").getString("url");
    }

    /**
     * 计算车辆停车的费用
     * @param endDateStr
     * @param parkingRecord
     */
    public int getTotalFee(String endDateStr, ParkingRecord parkingRecord) {
        ApiResult<ParkingTotalFeeDto> apiResult=parkingLotFeignClient.getParkingTotalFeeWithString(parkingRecord.getParkingLotCode(),
                DateUtils.getDateStr(parkingRecord.getInTime()),endDateStr);
        int totalFee=0;
        if (apiResult.getCode()==2000){
            totalFee=apiResult.getResult().getTotalFee();
        }
        if (parkingRecord.getEnableMonitor()==1){//开启哨兵
            int parkingTime = (int)(DateUtils.string2Date(endDateStr).getTime() - parkingRecord.getInTime().getTime()) /1000;
            int monitorFee=((parkingTime - 1)/Constants.monitor_time_section + 1) * Constants.monitor_Fee_section;
            totalFee=totalFee+monitorFee;
        }
        return totalFee;
    }

    /**
     * 检查车辆缴费总额是否足够给实际停车消费总额
     * @param endDateStr
     * @param parkingRecord
     * @param prePayRecord 预缴记录
     * @return
     */
   public PayRecord checkPay(String endDateStr, ParkingRecord parkingRecord, PayRecord prePayRecord){
       int fee = getTotalFee(endDateStr, parkingRecord);
      if (prePayRecord==null || (prePayRecord!=null && prePayRecord.getAmount()<fee)){
          PayRecord owePayRecord=new PayRecord();
          owePayRecord.setPayState(false);
          owePayRecord.setPaySource(0);
          owePayRecord.setPayType(2);
          owePayRecord.setRecordType(3);
          owePayRecord.setParkingRecordId(parkingRecord.getId());
          if (prePayRecord!=null){
              owePayRecord.setId(prePayRecord.getUserId()+1+System.currentTimeMillis());
              owePayRecord.setUserId(prePayRecord.getUserId());
              owePayRecord.setAmount(fee - prePayRecord.getAmount());
              owePayRecord.setTime(prePayRecord.getTime());
              owePayRecord.setEnableMonitor(prePayRecord.getEnableMonitor());
          }else {
              owePayRecord.setId("00000000000000001"+System.currentTimeMillis());
              owePayRecord.setAmount(fee);
          }
          return  owePayRecord;

      }
      return null;
   }


    /**
     * 封装进场消息
     * @param inForm
     * @param slotCode
     * @param recordId
     * @return
     */
    public EntryEnterDTO packCarInMessage(InParkingRecordForm inForm, String slotCode, String recordId){
        EntryEnterDTO inMessage=new EntryEnterDTO();
        inMessage.setSystemType(2);
        inMessage.setParkingLotCode(inForm.getParkingLotCode());
        inMessage.setParkingLotSlotCode(slotCode);
        inMessage.setEnterDateTime(DateUtils.stringToLocalDateTime(inForm.getInTime()));
        inMessage.setLocalRecordId(recordId);
        inMessage.setParkingDetectType(1);
        inMessage.setParkingType(0);
        return inMessage;
    }

    /**
     *  封装出场数据
     * @param record
     * @param prePayRecord 预缴记录
     * @param owePayRecord 欠缴记录
     * @return
     */
    public EntryLeaveDTO packCarOutMessage(ParkingRecord record,PayRecord prePayRecord,PayRecord owePayRecord){
        int feeTotal=0;
        int paidTotal=0;
        if (prePayRecord!=null){//有预缴
            feeTotal=prePayRecord.getAmount();
            paidTotal=prePayRecord.getAmount();
        }
        if (owePayRecord!=null){//有欠缴
            feeTotal=feeTotal+owePayRecord.getAmount();
        }
        EntryLeaveDTO outMessage=new EntryLeaveDTO();
        outMessage.setFeeTotal(feeTotal);
        outMessage.setPaidTotal(paidTotal);
        outMessage.setSystemType(2);
        outMessage.setBatteryChargingDuration(00000);
        outMessage.setDiscountTotal(0);
        outMessage.setEnterDateTime(DateUtils.dataToLocalDateTime(record.getInTime()));
        outMessage.setLeaveTime(DateUtils.dataToLocalDateTime(record.getOutTime()));
        outMessage.setLocalRecordId(record.getId());
        outMessage.setIsBatteryCharged(record.getIsCharging()==false?0:1);
        outMessage.setParkingDetectType(1);
        outMessage.setParkingDuration((int)(record.getOutTime().getTime()-record.getInTime().getTime())/1000);
        outMessage.setParkingLotCode(record.getParkingLotCode());
        outMessage.setParkingLotSlotCode(record.getParkingLotSlotCode());
        outMessage.setParkingRecordCode("");
        outMessage.setParkingType(0);
        return outMessage;
    }
}
